<template>
	
	<div class="layui-form-item">
		<label class="layui-form-label" v-if="title">{{title}}</label>
		<div class="layui-input-block">
			<view class="layui-unselect layui-form-radio" @click="change(index)" :class="{'layui-form-radioed':curIndex == index}"  v-for="(item,index) in list" :key="index">
				<i class="layui-anim layui-icon layui-icon-radio animated bounceIn"></i>
				<div>{{item[titleKey]}}</div>
			</view>
			<input type="text" :value="curVal" :name="name" style="display: none;">
		</div>
	</div>
	
</template>

<script>
	export default {
		name: "radioGroup",
		props: {
			name: {
				type: String,
				default: ''
			},
			list: {
				type: Array,
				default: function() {
					return [];
				}
			},
			value: {
				type: [String, Number,Boolean , Object , Array],
				default: ''
			},
			titleKey : { //说明文字的主键
				type: String,
				default: 'title'
			},
			valueKey : { //值的主键
				type: String,
				default: 'value'
			},
			title : { //说明文字的主键
				type: String,
				default: ''
			}
		},

		created() {
			this.setDefaultValue();
		},
		
		watch:{
			list : function(){
				this.setDefaultValue();
			},
			value : function(e){
				this.setDefaultValue();
			},
		},

		data() {
			return {
				curVal : '' ,
				curIndex : -1
			};
		},
		
		methods:{
			change : function(index){
				if (this.curIndex == index) {
					return false ;
				}
				this.curIndex = index ;
				this.curVal = this.list[index][this.valueKey] ;
				this.$emit("change" , this.curVal);
			},
			
			setDefaultValue : function(e){
				this.curVal = this.value ;
				for (var i = 0; i < this.list.length; i++) {
					var cur = this.list[i] ;
					if (cur[this.valueKey] === this.curVal) {
						this.curIndex = i ;
						break ;
					}
				}
				if (this.curIndex == -1 && this.list.length > 0) {
					this.curIndex = 0 ;
					this.curVal = this.list[0][this.valueKey] ;
				}
			},
		}
	}
</script>

<style>

</style>
